package vip.xiaonuo.sys.modular.wechat.checkin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.sys.api.dto.req.WechatCheckinReqDto;
import vip.xiaonuo.sys.api.dto.resp.WechatCheckinRespDto;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;
import vip.xiaonuo.sys.modular.wechat.api.dto.WechatCheckinResponse;
import vip.xiaonuo.sys.modular.wechat.api.service.WechatService;
import vip.xiaonuo.sys.modular.wechat.checkin.entity.WechatCheckinData;
import vip.xiaonuo.sys.modular.wechat.checkin.mapper.WechatCheckinDataMapper;
import vip.xiaonuo.sys.modular.wechat.checkin.service.WechatCheckinDataService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/7/16 13:40
 */
@Service
@RequiredArgsConstructor
public class WechatCheckinDataServiceImpl implements WechatCheckinDataService {

    private final SysUserService sysUserService;

    private final WechatService wechatService;

    private final WechatCheckinDataMapper checkinDataMapper;

    /**
     * 批量保存考勤数据
     */
    @Override
    public void syncCheckin() {
        List<SysUser> sysUserList = sysUserService.getAllUser();
        List<SysUser> filterSysUserList = sysUserList.stream().filter(s -> StringUtils.isNotBlank(s.getEmpNo())).toList();
        Map<String, SysUser> sysUserMap = filterSysUserList.stream()
                .collect(Collectors.toMap(
                        SysUser::getEmpNo,
                        Function.identity(),
                        (oldValue, newValue) -> oldValue));
        List<List<String>> empNoSetBatch = Lists.partition(new ArrayList<>(sysUserMap.keySet()), 80);
        String currentTime = CommonDateUtil.getCurrentTimeStr();
//        String beforeTime = CommonDateUtil.getTimeBeforeOrAfterMinutes(null, -15);
        String beforeTime = CommonDateUtil.getCurrentMonthFirstDay() + " 08:30:00";
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            empNoSetBatch.forEach(batch ->
                    executor.submit(() -> {
                        WechatCheckinResponse checkinResponse = wechatService.getCheckinRecord(currentTime, beforeTime, batch);
                        if (CollectionUtil.isNotEmpty(checkinResponse.getCheckindata())) {
                            for (WechatCheckinData checkinData : checkinResponse.getCheckindata()) {
                                SysUser sysUse = sysUserMap.get(checkinData.getUserid());
                                checkinData.setSysUser(Long.valueOf(sysUse.getId()));
                            }
                            String sql = checkinResponse.getCheckindata().stream()
                                    .map(s -> String.format("('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
                                            escapeSql(String.valueOf(s.getSysUser())),
                                            escapeSql(s.getUserid()),
                                            escapeSql(s.getGroupname()),
                                            escapeSql(s.getCheckin_type()),
                                            escapeSql(s.getException_type()),
                                            escapeSql(CommonDateUtil.uint32StrToDate(s.getCheckin_time())),
                                            escapeSql(s.getLocation_title()),
                                            escapeSql(s.getLocation_detail()),
                                            escapeSql(s.getWifiname()),
                                            escapeSql(s.getNotes()),
                                            escapeSql(s.getWifimac()),
                                            escapeSql(s.getMediaids().toString()),
                                            escapeSql(String.valueOf(s.getLat())),
                                            escapeSql(String.valueOf(s.getLng())),
                                            escapeSql(s.getDeviceid()),
                                            escapeSql(s.getSch_checkin_time()),
                                            escapeSql(String.valueOf(s.getGroupid())),
                                            escapeSql(String.valueOf(s.getTimeline_id()))
                                    )).collect(Collectors.joining(", "));
                            checkinDataMapper.insertBatch(sql.replace("'null'", "null"));
                        }
                    })
            );
        }
    }

    /**
     * 获取打卡记录
     *
     * @param checkinReqDto
     */
    @Override
    public List<WechatCheckinRespDto> getCheckinList(WechatCheckinReqDto checkinReqDto) {
        List<WechatCheckinData> checkinDataList = checkinDataMapper.selectList(Wrappers.<WechatCheckinData>lambdaQuery()
                .between(WechatCheckinData::getCheckin_time, checkinReqDto.getBeginTime(), checkinReqDto.getEndTime()));
        List<WechatCheckinRespDto> checkinRespDtoList = new ArrayList<>();
        BeanUtils.copyProperties(checkinDataList, checkinRespDtoList);
        return checkinRespDtoList;
    }
}
